import axios from 'axios'
import { baseURL, requestTimeout } from '@/config/index'
import { ElMessage } from 'element-plus'
import qs from 'qs'

const instance = axios.create({
  baseURL,
  timeout: requestTimeout,
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded;charset=UTF-8'
  }
})

/**
 * axios请求拦截器
 */

function jsonProp(obj) {
  // type check
  if (!obj || typeof obj !== 'object') {
    return obj
  }
  Object.keys(obj).forEach((key) => {
    if (typeof obj[key] === 'object') {
      obj[key] = JSON.stringify(obj[key])
    }
  })
  return obj
}

instance.interceptors.request.use(
  (config) => {
    // 发送请求之前做某件事
    if (
      config.data &&
      config.method === 'post' &&
      config.url.indexOf('/UploadServlet') < 0
    ) {
      config.data = qs.stringify(jsonProp(config.data))
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  }
)

/**
 * 响应拦截器
 */
instance.interceptors.response.use(
  (response) => {
    return new Promise((resolve) => {
      resolve(response)
      // setTimeout(() => {
      //
      // }, 500)
    })
  },
  (error) => {
    ElMessage.error('请求错误')
    return Promise.reject(error)
  }
)

export default instance
